<?php
/**
 * Created by PhpStorm.
 * User: allen
 * Date: 2019/4/21
 * Time: 10:10 PM
 */

class Solution
{
    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    public function addTwoNumbers($l1, $l2)
    {
        $listNode1 = $l1;
        $listNode2 = $l2;
        $res = new ListNode(0);
        $curr = $res;
        $carry = 0;
        while ($listNode1 !== null || $listNode2 !== null) {
            $total = ($listNode1 == null ? 0 : $listNode1->val) + ($listNode2 == null ? 0 : $listNode2->val) + $carry;
            $carry = intval($total / 10);
            $curr->next = new ListNode($total % 10);
            $curr = $curr->next;
            // $curr = new ListNode($total % 10);

            if ($listNode1 != null) {
                $listNode1 = $listNode1->next;
            }

            if ($listNode2 != null) {
                $listNode2 = $listNode2->next;
            }

        }

        if ($carry > 0) {
            $curr->next = new ListNode($carry);
        }

        return $res->next;
    }
}

class ListNode
{
    public $val = 0;
    public $next = null;

    function __construct($val)
    {
        $this->val = $val;
    }
}

$l1 = [2, 4, 3];
$l2 = [5, 6, 4];
$res = (new Solution())->addTwoNumbers(new ListNode($l1[1]),new ListNode($l2[1]));
print_r($res);